package com.sinszm.web.request;

import org.springframework.core.Ordered;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 处理请求流多次使用问题
 *
 * @author chenjianbo
 */
@WebFilter
public class MRequestFilter implements Filter, Ordered {

    private static final String[] MEDIAS = {
            "text/plain",
            "application/json",
            "application/xml",
            "text/xml"
    };

    @Override
    public void init(FilterConfig filterConfig) {

    }

    /**
     * 验证Content-Type类型，对常规的post流请求类型进行判断
     *
     * @param contentType contentType
     * @return            状态
     */
    private boolean isMedia(String contentType) {
        if (contentType == null || "".equals(contentType.trim())) {
            return false;
        }
        for (String media : MEDIAS) {
            if (contentType.toLowerCase().trim().contains(media)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
            ServletException {
        ServletRequest wrapper = null;
        if (request instanceof HttpServletRequest && isMedia(request.getContentType())) {
            wrapper = new MRequestWrapper((HttpServletRequest) request);
        }
        if (wrapper == null) {
            chain.doFilter(request, response);
        } else {
            chain.doFilter(wrapper, response);
        }
    }

    @Override
    public void destroy() {

    }

    @Override
    public int getOrder() {
        return 0;
    }

}
